package com.stef.MMH;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.stef.MMH.datatypes.User;

public class RegisterServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		EntityManager em = EmfHolder.getEntityManager();
		if (!em.getTransaction().isActive()) {
			em.getTransaction().begin();
		}

		// TODO Auto-generated method stub

		Map<String, String[]> paramMap = req.getParameterMap();
		boolean validSubmission = true;
		for (Map.Entry<String, String[]> en : paramMap.entrySet()) {
			if (en.getValue()[0].length() < 1) {
				resp.getWriter().println("Missing value for " + en.getKey());
				validSubmission = false;
			}
		}

		if (validSubmission) {

			String realName = URLEncoder.encode(req.getParameter("name"),
					"UTF-8");
			String userName = URLEncoder.encode(req.getParameter("username"),
					"UTF-8");
			String emailAddress = URLEncoder.encode(req.getParameter("email"),
					"UTF-8");
			String password = URLEncoder.encode(req.getParameter("password"),
					"UTF-8");

			User newUser = new User(userName, emailAddress, password, realName);

			Query q = em.createQuery("SELECT x FROM User x WHERE x.email = \""
					+ emailAddress + "\"");
			if (q.getResultList().size() > 0) {
				resp.getWriter().println("Email already exists");
			} else {
				em.persist(newUser);
				
				resp.getWriter().println(
						"New User Created with following details:");
				resp.getWriter().println("Name: " + newUser.getRealName());
				resp.getWriter().println("Email: " + newUser.getEmail());
				resp.getWriter().println(
						"Password: " + newUser.getPasswordHash());
				resp.getWriter().println("Username: " + newUser.getUserName());
				System.out.println("Registered User ");
			}
		} else {
			resp.getWriter().println("Try AGAIN, LOL!!");
		}
		em.getTransaction().commit();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req, resp);
	}

}
